package cn.chendd.bootsrtap.service.impl;

import cn.chendd.bootsrtap.client.GoodLuckClient;
import cn.chendd.bootsrtap.client.UsersClient;
import cn.chendd.bootsrtap.service.TransactionalService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 验证事务接口实现
 *
 * @author chendd
 * @date 2023/1/20 16:29
 */
@Service
public class TransactionalServiceImpl implements TransactionalService {

    @Resource
    private UsersClient usersClient;
    @Resource
    private GoodLuckClient goodLuckClient;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void saveDataCommit() {
        System.out.println("TX_XID--->" + RootContext.getXID());
        //两个接口保存成功，事务提交
        this.usersClient.insertSuccess();
        this.goodLuckClient.insertSuccess();
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void saveDataRollback1() {
        //第一个保存成功，第二个保存失败，事务回滚
        System.out.println("TX_XID--->" + RootContext.getXID());
        this.usersClient.insertSuccess();
        this.goodLuckClient.insertException();
        System.out.println("TransactionalServiceImpl.saveDataRollback1");
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void saveDataRollback2() {
        //第一个保存成功，第二个保存成功，但后续逻辑出现运行时异常，事务回滚
        System.out.println("TX_XID--->" + RootContext.getXID());
        this.usersClient.insertSuccess();
        this.goodLuckClient.insertSuccess();
        System.out.println("TransactionalServiceImpl.saveDataRollback2---" + (1 / 0));
    }

}
